Ext.namespace("admin.security");

admin.security.user = function(panelId, title, iconClz){

    /** user grid start **/
	var userStore = new Ext.data.JsonStore({
		url : "admin/user/findUserByCon",
		totalProperty : "total",
		root : "rows",
		autoLoad : true,
		fields : ["id", "createDate", "updateDate", "accountExpired", "accountLocked",
			"credentialsExpired", "status", "des", "realName", "username"
		],
		listeners : {
			beforeload : function(s){
				s.removeAll();
				Ext.apply(s.baseParams, {
					status : statusCombo.getValue(),
					con : queryField.getValue()
				});
			}
		}
	});
    var userSm = new Ext.grid.RowSelectionModel({
        singleSelect : true,
        listeners : {
            rowselect : function(){
                var rec = userSm.getSelected();
                ajaxRequest({
                    url : "admin/role/listRoleByUser/" + rec.get("id"),
                    callback : cb
                });
                //返回需为ExtReturn，带success信息,从而执行callback
                function cb(json){
                    userSelectFlag = false;
                    var role = $.makeArray(json.data);
                    var roleNum = roleStore.getTotalCount();
                    var range = [];
                    $.each(role, function(n, v){
                        for(var i=0; i<roleNum; i++){
                            var rec = roleStore.getAt(i);
                            if(rec.get("id")===v["id"]){
                                range.push(i);
                            }
                        }
                    });
                    //选择区域之前将其他已选区域取消选择
                    roleSm.selectRows(range);
                    userSelectFlag = true;
                }
            }
        }
    });
	var userCm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
		header : "用户名",
		dataIndex : "username"
	}, {
		header : "姓名",
		dataIndex : "realName"
	}, {
		header : "状态",
		dataIndex : "status",
		renderer : renderStatus
	}, {
		header : "创建时间",
		dataIndex : "createDate",
		renderer : renderDate,
		width : 120
	}, {
		header : "更新时间",
		dataIndex : "updateDate",
		renderer : renderDate,
		width : 120
	}, {
		header : "描述",
		dataIndex : "des"
	}]);
	var resetPwdBtn = {
		text : "重置密码",
		iconCls : "reset",
		handler : resetPwd
	};
	var optBar = genOptBarByFn(create, null, update, toggle, importIn);

	optBar.push(resetPwdBtn);
	var statusCombo = genQueryStatusCombo();
	var queryField = new Ext.form.TextField({
		width : 100
	});
	var queryBar = ["状态:", statusCombo, "关键字:", queryField, {
		text : "查询",
		iconCls : "query",
		handler : function(){
			userStore.reload();
		}
	}];
	var userGrid = new Ext.grid.GridPanel({
		store : userStore,
		sm : userSm,
		cm : userCm,
        flex : 6,
		tbar : genToolBar(optBar, queryBar, panelId),
		bbar : genPageBar(userStore)
	});
    /** user grid end **/

    /** role grid start **/
    var roleStore = new Ext.data.JsonStore({
        url : "admin/role/findRoleByCon",
        totalProperty : "total",
        root : "rows",
        autoLoad : true,
        fields : ["id", "createTime", "updateTime", "des", "roleName", "isRoot", "status"],
        listeners : {
            beforeload : function(s){
                s.removeAll();
                Ext.apply(s.baseParams, {
                    status : 1, //必须是启用的role
                    con : roleQueryField.getValue()
                });
            }
        }
    });
    var roleSm = new Ext.grid.CheckboxSelectionModel({
        checkOnly : true,
        listeners : {
            rowdeselect : deleteRole,
            rowselect : addRole
        }
    });
    var roleCm = new Ext.grid.ColumnModel([roleSm, new Ext.grid.RowNumberer(), {
        header : "名称",
        dataIndex : "roleName",
        width : 150
    }, {
        header : "状态",
        dataIndex : "status",
        renderer : renderStatus
    }, {
        header : "描述",
        dataIndex : "des"
    }]);
    var roleQueryField = genQueryField();
    var roleQueryBar = [ "->", roleQueryField, {
        text : "查询",
        iconCls : "query",
        handler : function(){
            roleStore.reload();
        }
    }];
    var roleGrid = new Ext.grid.GridPanel({
        title : "关联角色",
        frame : true,
        sm : roleSm,
        cm : roleCm,
        store : roleStore,
        tbar : genToolBar([], roleQueryBar, panelId),
        flex : 4
    });
    /** role grid end **/

	return new Ext.Panel({
		id : panelId,
		title : title,
		iconCls : iconClz,
		closable : true,
        layout : "hbox",
        layoutConfig : {
            align : "stretch"
        },
        items : [userGrid, roleGrid]
	});

	function genAddOrUpdateWin(url){
		return new Ext.Window({
			title : "新增或更新用户",
			layout : "fit",
			modal : true,
			iconCls : "save",
			width : 300,
			height : 250,
			plain : true,
			bodyStyle : 'padding:5px;',
			items : genForm(url)
		});
		function genForm(url){
			return new Ext.form.FormPanel({
				url : url,
				labelWidth : 50,
				labelAlign : "right",
				baseCls: 'x-plain',
				defaults : {
					xtype : "textfield",
					anchor : "95%"
				},
				items : [{
					xtype : "hidden",
					name : "id",
					value : "-1"
				}, {
					fieldLabel:"用户名",
					name : "username"
				}, {
					fieldLabel : "姓名",
					name : "realName"
				}, genStatusCombo(), {
					fieldLabel : "描述",
					name : "des",
					xtype : "textarea"
				}],
				buttonAlign : "center",
				buttons : [{
					text : "保存",
					iconCls : "save",
					handler : function(b){
						submitForm(b.findParentByType("form"), refreshGrid);
						function refreshGrid(){
							userStore.reload();
						}
					}
				}, {
					text : "重置",
					iconCls : "reset",
					type : "reset",
					handler : function(b){
						b.findParentByType("form").getForm().reset();
					}
				}]
			});
		}
	}
	function create(){
		var win = genAddOrUpdateWin("admin/user/add");
		win.show();
	}
	function del(){
		var rec =userSm.getSelected();
		if(rec==null){
			showFailMsg("请选择用户");
			return;
		}
		ajaxRequest({
			url : "admin/user/delete/" + rec.get("id"),
			callback : function(){
				userStore.reload();
			}
		});
	}
	function update(){
		var rec =userSm.getSelected();
		if(rec==null){
			showFailMsg("请选择用户");
			return;
		}
		var win = genAddOrUpdateWin("admin/user/update");
		win.findByType("form")[0].getForm().loadRecord(rec);
		win.findByType("form")[0].get(1).setReadOnly(true);
		win.show();
	}
	function toggle(){
		var rec =userSm.getSelected();
		if(rec==null){
			showFailMsg("请选择用户");
			return;
		}
		ajaxRequest({
			url : "admin/user/toggleStatus/" + rec.get("id"),
			callback : function(){
				userStore.reload();
			}
		});
	}
	function importIn(){
		var form = new Ext.form.FormPanel({
			fileUpload : true,
			frame : true,
			labelWidth: 30,
			url : "admin/user/importIn",
			defaults : {
				anchor : "100%"
			},
			items : [{
				fieldLabel : "文件",
				emptyText: '请选择文件',
				anchor: '100%',
				allowBlank: false,
				xtype : "fileuploadfield",
				name : 'file',
				buttonText : "浏览"
			}],
			buttons : [{
				text : "确定",
				iconCls : "save",
				handler : function(b){
					submitForm(b.findParentByType("form"), refreshGrid);
					function refreshGrid(){
					}
				}
			}, {
				text : "重置",
				iconCls : "reset",
				handler : function(b){
					b.findParentByType("form").getForm().reset();
				}
			}]
		});
		var win = new Ext.Window({
			title : "上传文件",
			width : 300,
			height : 100,
			layout : "fit",
			frame : true,
			items : [form]
		});
		win.show();
	}
	function resetPwd(){
		var rec =userSm.getSelected();
		if(rec==null){
			showFailMsg("请选择用户");
			return;
		}
		ajaxRequest({
			url : "admin/user/resetPwd/" + rec.get("id")
		});
	}

    function addRole(sm, rowIndex){
        if(userSelectFlag===false){
            return;
        }
        var userRec = userSm.getSelected();
        if(userRec==null){
            showFailMsg("请选择教师.");
            return;
        }
        ajaxRequest({
            url : "admin/userRole/add",
            params : {
                userId : userRec.get("id"),
                roleId : roleStore.getAt(rowIndex).get("id")
            }
        });
    }
    function deleteRole(sm, rowIndex){
        if(userSelectFlag===false){
            return;
        }
        var userRec = userSm.getSelected();
        if(userRec==null){
            showFailMsg("请选择教师.");
            return;
        }
        ajaxRequest({
            url : "admin/userRole/delete",
            params : {
                userId : userRec.get("id"),
                roleId : roleStore.getAt(rowIndex).get("id")
            }
        });
    }

}

registerModule("admin.security.user", admin.security.user);